let variable = require('../../data/variable.js');
let gameData = require('../../util/gameData.js');
let util = require('../../util/util.js');
let log = require('../../util/log.js');
let save = require('../save.js');

module.exports = Status;

Status.statusID = {
    Idle: 0,		// 空闲
    Deal: 1,        // 发牌
    Bid: 2,		    // 叫分
    Ask: 3,         // 叫地主
    Grab: 4,		// 抢地主
    Double: 5,       // 加倍
    Playing: 6,	    // 开局
    Over: 7,		// 结算
    Loss: 8,		// 流局
};
let statusName = ['Idle', 'Deal', 'Bid', 'Ask', 'Grab', 'Double', 'Playing', 'Over', 'Loss'];
function Status(id) {
    this._id = id;
}

// 返回指定状态的超时时间
Status.getTimeout = function (id) {
    return statusTimeout[id];
};

Status.createState = function (id) {
    log.d('createState:', id);
    let ss = [Idle, Deal, Bid, Ask, Grab, Double, Playing, Over, Loss];
    let obj = new ss[id];
    obj.id = id;
    return obj;
};
Status.getStateName = function (id) {
    return statusName[id];
};
///空闲状态
function Idle() {
}
Idle.prototype.onTimeout = function (table) {
    table.setState(table.nextStateId());
};
Idle.prototype.onEnter = function (table) {
};
Idle.prototype.onExit = function (table) {
};

//发牌阶段
function Deal() {

}
Deal.prototype.onEnter = function (table) {
    table.broadcast('gameDealStart');
    table._multiple = gameData.d.gameLv[table.getGameLv()].baseMultiple;
    table.onStart(table);
    table.setTimeout(function () {
        table.setState(table.nextStateId())
    }, gameData.d.config.dealTimeout);
};
Deal.prototype.onExit = function (table) {
    table.broadcast('gameDealEnd');
};

///叫分状态
function Bid() {
}
Bid.prototype.onEnter = function (table) {
    //log.d('进入叫分状态', table);
    table.onStart(table);
    table.broadcast('gameAskChipStart', {'local': table.getPlayID()});
    this.setTimeout(table);
};
Bid.prototype.onExit = function (table) {
    log.d('离开叫分状态');
    table._askInfo = [];
    let gameAskChipEnd = {};
    gameAskChipEnd.dz = table.getDZ();
    gameAskChipEnd.desktopCards = table.getHoleCards();
    table.broadcast('gameAskChipEnd', gameAskChipEnd);
    table.emit("bidOver");
};
Bid.prototype.setTimeout = function (table) {
    //table.setTimeout(function () {
    //    table.askScore(table._playID, 0);
    //}, gameData.d.config.askChipTimeout);
    let player = table.getCurrentPlayer();
    let onTimeout = function () {
        //if (!player.isAutoPlay()) {
        //    table.addManaged(table.getPlayID(), true);
        //}
        table.autoRun();
    };

    let onAutoPlay = function () {
        table.autoRun();
    };

    if (player.isAutoPlay()) {
        table.setTimeout(onAutoPlay, gameData.d.config.autoAskChipTime);
    }
    else {
        table.setTimeout(onTimeout, gameData.d.config.askChipTimeout);
    }
};

///叫分状态
function Ask() {
}
Ask.prototype.onEnter = function (table) {
    //log.d('进入叫分状态', table);
    table.broadcast('gameAskDZStart', {'local': table.getPlayID()});
    this.setTimeout(table);
};
Ask.prototype.onExit = function (table) {
    log.d('离开叫地主状态');
    //let gameAskChipEnd = {};
    //gameAskChipEnd.dz = table.getDZ();
    //gameAskChipEnd.desktopCards = table.getHoleCards();
    //table.broadcast('gameAskDZEnd', gameAskChipEnd);
    table.broadcast('gameAskDZEnd');
};
Ask.prototype.setTimeout = function (table) {
    let player = table.getCurrentPlayer();
    let onTimeout = function () {
        table.autoRun();
    };

    let onAutoPlay = function () {
        table.autoRun();
    };

    if (player.isAutoPlay()) {
        table.setTimeout(onAutoPlay, gameData.d.config.autoAskChipTime);
    }
    else {
        table.setTimeout(onTimeout, gameData.d.config.askChipTimeout);
    }
};

///抢地主
function Grab() {
}
Grab.prototype.onEnter = function (table) {

    // 1,先找出可以参与抢地主的玩家,排除PASS的玩家
    //log.d('askInfo:',table._askInfo);
    let info = table._askInfo;
    let temp = [0, 1, 2];	// candidate list
    for (let i in info) {
        temp.splice(info[i], 1);
    }
    table._dzID = table.getPlayID();
    log.d('地主人选:', temp);
    if (temp.length == 1) {
        log.d('只有一个玩家叫分,所以直接进入游戏状态');
        return table.setState(table.nextStateId());
    }
    table._askInfo = [];
    table._dzList = temp;
    log.d('当前由' + table.getPlayID() + '叫地主');

    // temp 中保存可以参与抢地主的座位ID
    for (let i = 0; i < temp.length; i++) {
        if (table.getPlayID() == temp[i]) {
            table._playID = (i + 1) % 3;
            break;
        }
    }
    log.d('由' + temp[table.getPlayID()] + '抢地主', temp);
    table.broadcast('gameRobDZStart', {'local': temp[table.getPlayID()]});
    this.setTimeout(table);
};
Grab.prototype.onExit = function (table) {
    let gameRobDZEnd = {};
    gameRobDZEnd.dz = table.getDZ();
    gameRobDZEnd.desktopCards = table.getHoleCards();
    table.broadcast('gameRobDZEnd', gameRobDZEnd);
    table.emit("bidOver");
};
Grab.prototype.setTimeout = function (table) {
    let player = table.getCurrentRobPlayer();
    let onTimeout = function () {
        table.autoRun();
    };

    let onAutoPlay = function () {
        table.autoRun();
    };

    if (player.isAutoPlay()) {
        table.setTimeout(onAutoPlay, gameData.d.config.autoAskChipTime);
    }
    else {
        table.setTimeout(onTimeout, gameData.d.config.askChipTimeout);
    }
};

//加倍阶段
function Double() {

}
Double.prototype.onEnter = function (table) {
    this._askInfo = [];
    let gameDoubleStart = {0: false, 1: false, 2: false};
    if (gameData.d.gameLv[table.getGameLv()].coinType === 'score') {
        gameDoubleStart = {0: true, 1: true, 2: true};
    } else {
        let coin = gameData.d.gameLv[table.getGameLv()].doubleCoin + table.getTicket();
        let dzCoin = table.getPlayer(table.getDZ()).getCoin();
        let nmCoin1 = table.getPlayer((table.getDZ() + 1) % 3).getCoin();
        let nmCoin2 = table.getPlayer((table.getDZ() + 2) % 3).getCoin();

        if (dzCoin > coin && nmCoin1 > coin && nmCoin2 > coin) {
            gameDoubleStart[table.getDZ()] = true;
        }
        if (dzCoin > coin && nmCoin1 > coin) {
            gameDoubleStart[(table.getDZ() + 1) % 3] = true;
        }
        if (dzCoin > coin && nmCoin2 > coin) {
            gameDoubleStart[(table.getDZ() + 2) % 3] = true;
        }
    }

    table.broadcast('gameDoubleStart', gameDoubleStart);
    //if (!gameDoubleStart[0] && !gameDoubleStart[1] && !gameDoubleStart[2]) {
    //    table.setState(table.nextStateId());
    //} else {
        table.setTimeout(function () {
            table.setState(table.nextStateId());
        }, gameData.d.config.doubleTimeout);
    //}
};
Double.prototype.onExit = function (table) {
    table.broadcast('gameDoubleEnd');
};

//开局状态
function Playing() {
}

Playing.prototype.onEnter = function (table) {
    table.startPlay();
    // setTimeout(function(){table.setState(Status.statusID.Over)}, 3000);
    //table.broadcast('gamePlayStart', {'local': table.getDZ(), 'chip': table.getMultiple()});
    table.broadcast('gamePlayStart', {'local': table.getDZ()});
    // 设置超时
    //log.d("设置超时");
    this.setTimeout(table);
};
Playing.prototype.onExit = function (table) {
    //clearInterval(this._timeOut);
    // 结束定时任务
    table.removeTimeout();
    log.d('离开游戏状态');
    table.broadcast('gamePlayEnd', {'local': table.getPlayID()});
};
Playing.prototype.setTimeout = function (table) {
    let player = table.getCurrentPlayer();
    let onTimeout = function () {
        //if (!player.isAutoPlay()) {
        table.addManaged(table.getPlayID(), true);
        //}
        //player.timeOutToAuto(table);
        //table.autoRun();
    };

    let onAutoPlay = function () {
        table.autoRun();
    };

    if (player.isAutoPlay()) {
        let time = 0;
        if (player.isRobot()) {
            time = util.random(gameData.d.config.robotPlayTimeA, gameData.d.config.robotPlayTimeB, 1)
                + (player.getCardsNum() * gameData.d.config.robotPlayTimeCardAdd);
        } else {
            time = gameData.d.config.autoPlayTime;
        }
        table.setTimeout(function () {
            table.autoRun();
        }, time);
    }
    else {
        let getPlayID = table.getPlayID();
        table.setTimeout(function () {
            //if (!player.isAutoPlay()) {
            table.addManaged(getPlayID, true);
            //}
            //player.timeOutToAuto(table);
        }, gameData.d.config.playTimeout);
    }
};
///结算状态
function Over() {
}
//判断春天
//返回: 春天:1,反春-1,普通:0
Over.prototype.isSpring = function (table) {

    let history = table.getHistory();
    let dz = history[0];		//第一个出牌的是地主.
    let n = 0;					//统计地主出牌的次数.
    for (let i in history) {
        if (history[i] == dz)
            n++;
    }
    if (n == history.length)
        return 1;
    else if (n == 1)
        return -1;
    else
        return 0;
};
Over.prototype.onEnter = function (table, winnerSeat) {
    //开始结算,底分,倍数
    let baseScore = table.getBaseScore();
    let multiple = table.getMultiple();
    let ticket = table.getTicket();
    //谁赢了? 取最后一次操作的玩家ID
    let winner = table.getPlayer(winnerSeat);
    if (winner.getCardsNum() > 0)
        return;
    //判断春天(或者反春),底分翻倍
    let spring = this.isSpring(table);
    if (spring != 0)
        multiple *= 2;
    //
    let score = baseScore * multiple;
    let result = [];

    //if (winnerSeat == table.getDZ()) {
    //    //如果是地主赢
    //    let coin = Math.min(score * 2, winner.getCoin() + table.getFree());
    //    result[winnerSeat] = (coin > table.getWinCap()) ? table.getWinCap() : coin;
    //    result[(winnerSeat + 1) % 3] = parseInt(-coin / 2);
    //    result[(winnerSeat + 2) % 3] = parseInt(-coin / 2);
    //    log.d('结算:' + spring, '底分:' + baseScore, ' 房费:' + ticket, ' 倍数:' + multiple, ' 胜者:地主');
    //} else {
    //    //如果是农民赢
    //    let coin = Math.min(score, winner.getCoin());
    //    result[winnerSeat] = coin;
    //    result[(winnerSeat + 1) % 3] = (coin > table.getWinCap()) ? table.getWinCap() : coin;
    //    result[(winnerSeat + 2) % 3] = (coin > table.getWinCap()) ? table.getWinCap() : coin;
    //    result[table.getDZ()] = -coin * 2;
    //    log.d('结算:' + spring, '底分:' + baseScore, ' 房费:' + ticket, ' 倍数:' + multiple, ' 胜者:农民');
    //}

    if (winnerSeat == table.getDZ()) {
        //如果是地主赢
        //let coin0 = score * (table.getPlayer((winnerSeat + 1) % 3).getDouble() + table.getPlayer((winnerSeat + 2) % 3).getDouble());
        let coin1 = score * table.getPlayer((winnerSeat + 1) % 3).getDouble();
        let coin2 = score * table.getPlayer((winnerSeat + 2) % 3).getDouble();
        if (gameData.d.gameLv[table.getGameLv()].coinType != 'score') {
            if (coin1 > table.getPlayer((winnerSeat + 1) % 3).getCoin() - ticket) {
                coin1 = table.getPlayer((winnerSeat + 1) % 3).getCoin() - ticket;
            }
            if (coin2 > table.getPlayer((winnerSeat + 2) % 3).getCoin() - ticket) {
                coin2 = table.getPlayer((winnerSeat + 2) % 3).getCoin() - ticket;
            }
        }
        let coin0 = coin1 + coin2;

        result[winnerSeat] = coin0;
        result[(winnerSeat + 1) % 3] = -coin1;
        result[(winnerSeat + 2) % 3] = -coin2;
        log.d('春天:' + spring, '底分:' + baseScore, ' 房费:' + ticket, ' 倍数:' + multiple, ' 胜者:地主');
    } else {
        //如果是农民赢
        let dzDouble = (table.getPlayer((table.getDZ() + 1) % 3).getDouble() + table.getPlayer((table.getDZ() + 2) % 3).getDouble());
        let coin0 = score * dzDouble;
        if (gameData.d.gameLv[table.getGameLv()].coinType != 'score') {
            if (coin0 > table.getPlayer(table.getDZ()).getCoin() - ticket) {
                coin0 = table.getPlayer(table.getDZ()).getCoin() - ticket;
            }
        }
        let coin1 = coin0 / dzDouble * table.getPlayer((table.getDZ() + 1) % 3).getDouble();
        let coin2 = coin0 / dzDouble * table.getPlayer((table.getDZ() + 2) % 3).getDouble();
        //let coin1 = Math.floor(coin0 / 2), coin2 = Math.floor(coin0 / 2);
        //coin0 = coin0 * table.getPlayer(table.getDZ()).getDouble();
        //coin1 = coin1 * table.getPlayer((table.getDZ() + 1) % 3).getDouble();
        //coin2 = coin2 * table.getPlayer((table.getDZ() + 2) % 3).getDouble();

        result[table.getDZ()] = -coin0;
        result[(table.getDZ() + 1) % 3] = Math.floor(coin1);
        result[(table.getDZ() + 2) % 3] = Math.floor(coin2);
        log.d('春天:' + spring, '底分:' + baseScore, ' 房费:' + ticket, ' 倍数:' + multiple, ' 胜者:农民');
    }
    let ids = [];
    ids[0] = table.getPlayer(0).getPid();
    ids[1] = table.getPlayer(1).getPid();
    ids[2] = table.getPlayer(2).getPid();

    let gameOver = null;
    switch (gameData.d.gameLv[table.getGameLv()].type) {
        case 'custom':
            gameOver = 'gameOverCustom';
            break;
        case 'happy':
        case 'match':
            gameOver = 'gameOver';
            break;
        case 'arena':
            gameOver = 'gameOverArena';
            break;
    }
    table.emit(gameOver, result, winnerSeat, ticket, spring, ids);

    return {
        'winner': winnerSeat,
        'roomId': table.getRoomId(),
        'tableId': table.getTableID(),
        'spring': spring,
        'result': result,
        'ids': ids
    };
};

Over.prototype.onExit = function (table) {
    log.d('离开结算状态');
};

///流局状态
function Loss() {
}
Loss.prototype.onEnter = function (table, source) {
    if (table.getLossTime() >= (gameData.d.config.playLossTime - 1)) {
        //log.d('多次流局，随机一人地主开始');
        switch (source) {
            case 'askScore':
                table.randAskScore();
                break;
            case 'askDZ':
                table.randAskDZ();
                break;
        }
    } else {
        table.addLossTime();
        table.restart();
        table.broadcast('gameLoss');
    }
};
Loss.prototype.onExit = function (table) {
};
